/*
* Format a string without accent
*/
String.prototype.whithoutAccent = function(){
    var accent = [
        /[\300-\306]/g, /[\340-\346]/g, // A, a
        /[\310-\313]/g, /[\350-\353]/g, // E, e
        /[\314-\317]/g, /[\354-\357]/g, // I, i
        /[\322-\330]/g, /[\362-\370]/g, // O, o
        /[\331-\334]/g, /[\371-\374]/g, // U, u
        /[\321]/g, /[\361]/g, // N, n
        /[\307]/g, /[\347]/g, // C, c
    ];
    var noaccent = ['A','a','E','e','I','i','O','o','U','u','N','n','C','c'];
     
    var str = this;
    for(var i = 0; i < accent.length; i++){
        str = str.replace(accent[i], noaccent[i]);
    }
     
    return str;
};

/**
* On document ready 
*/
$( document ).ready(function() 
{
	$('#accordion').find('.accordion-toggle').click(function()
	{
		  //Expand or collapse this panel
		  $(this).next().slideToggle('fast');

		  //Hide the other panels
		  $(".accordion-content").not($(this).next()).slideUp('fast');
	});
});

app.controller('documentscontroller', ['$scope', '$parse', '$http', function($scope, $parse, $http)
{
	$('#jqxTree').bind('select', function (event) 
	{
		var args = event.args;
		var item = $('#jqxTree').jqxTree('getItem', args.element);
		$scope.$apply(function () 
		{
			console.info("SelectedItem from jqxTree changed");
			$scope.downloadUrl = '';
			$scope.canDownload = false;
			item.path = item.path.replace("/", "\\");
			$scope.selectedItem = item;
			
			//clear the children of the selected node
			var $element = $(event.args.element);
			var children = $element.find('li');
			$.each(children, function () 
			{
				var item = $("#jqxTree").jqxTree('getItem', this);
				$("#jqxTree").jqxTree('removeItem', item);
			});
			
			//Set the parent item element
			var parentElement = event.args.element.parentElement.parentElement;
			$scope.parentElement = $('#jqxTree').jqxTree('getItem', parentElement);
			
			$scope.getDocuments(item.path);
			if($scope.selectedItem !== null)
			{	
				$('#alert').show();
				$scope.canManageDocument = true;
			}
			else
			{
				$scope.canManageDocument = false;
			}
		});
	});
	
	$("#jqxTree").on('dragEnd', function (event) 
	{  
		//get all items and push all path on the core
		var items = $('#jqxTree').jqxTree('getItems');
		
		items.forEach(function(item) 
		{
			var path = item.path;
			if(item.isfolder == false)
			{
				path += "/" + item.label;
			}
		});
		
		// get item's label.
		var itemLabel = event.args.label;
		// get item's value.
		var itemValue = event.args.value;
		// get the original dragStart event from the jqxDragDrop plug-in.
		var originalEvent = event.args.originalEvent;

		var x = event.args.originalEvent.pageX;
		var y = event.args.originalEvent.pageY;
		
		if (event.args.originalEvent.originalEvent.touches) 
		{
			var touch = event.args.originalEvent.originalEvent.changedTouches[0];
			x = touch.pageX;
			y = touch.pageY;
		}
		/*
		//Check difference between data before drag and after
		var newList = [];
		$("#jqxTree").jqxTree('getItems').forEach(function(entry) 
		{
			var path = entry.path;
			if(entry.isfolder == false)
			{
				path += "/" + entry.label;
			}
			newList.push(path);
		});
		var oldList = [];
		var source = $scope.getTreeviewDataSource();
		var array = JSON.parse(source);
		array.forEach(function(document) 
		{
			var path = document.Path + document.Name;
			oldList.push(path);
			if(oldList.indexOf(path) == -1)
			{
				
			}
		});
		*/
	});
	
	/**
	* Build the documents data source
	*/	
	$scope.buildData = function(data) 
	{
		console.info("buildData - called"); 
		console.info("buildData - start"); 
		var startTime = new Date();
		var source = [];
		var items = [];
		// build hierarchical source.
		for (i = 0; i < data.length; i++) 
		{
			var item = data[i];
			var label = item["Name"];
			var parentid = item["ParentId"];
			var id = item["Id"];
			var path = item["Path"];
			var isfolder = item["IsFolder"];
			
			if (items[parentid]) 
			{
				var item = { parentid: parentid, label: label, item: item, path: path, isfolder: isfolder };
				if (!items[parentid].items) {
					items[parentid].items = [];
				}
				items[parentid].items[items[parentid].items.length] = item;
				items[id] = item;
			}
			else 
			{
				items[id] = { parentid: parentid, label: label, item: item , path: path, isfolder: isfolder};
				source[id] = items[id];
			}
		}
		var endTime = new Date();
		var timeDiff = endTime - startTime;
		console.info("buildData - finished => " + timeDiff + " ms");
		return source;
	};
	
	/**
	* Get documents command
	*/
	$scope.getDocuments = function(path) 
	{
		console.info("getDocuments - called with path : " + path);
		$scope.loadingDocuments = true;

		$http.post($scope.servicebase, { "service" : "getDocuments", "root" : path, "forceToRefresh" : true, "filter" : $scope.documentFilter }).
		success(function(data, status) 
		{
			console.info("getDocuments - call success");
			$scope.status = status;
			$scope.data = data;
			$scope.result = data;
			console.info("result of getDocuments : " + JSON.stringify($scope.data)); 	
			if(data.isFailed == true)
			{
				$scope.setMessageCommand($scope.data.exception, 'danger');
			}
			else
			{
				if(data.response != undefined)
				{
					var source = $scope.buildData(data.response);

					if($scope.selectedItem == '' || $scope.selectedItem == null)
					{
						$('#jqxTree').jqxTree({ allowDrag:true, allowDrop:true, source: source, width: '100%', height: '400px'});
					}
					else if($scope.selectedItem != '' && $scope.selectedItem.isfolder)
					{
						$("#jqxTree").jqxTree('addTo', source, $scope.selectedItem);
						$("#jqxTree").jqxTree('expandItem', $scope.selectedItem);
					}
				}
				$scope.loadingDocuments = false;
			}
		})
		.
		error(function(data, status) 
		{
			console.error("getDocuments - call failed"); 
			$scope.loadingDocuments = false;
			//$scope.canManageTree = true;
			$scope.data = data || "Request failed";
			$scope.status = status;			
			console.error($scope.data); 
			console.error("getDocuments - data : " + $scope.data); 						
		});
	};
	
	/**
	* Cancel the selected document
	*/
	$scope.cancelSelectedDocumentCommand = function()
	{
		$('#alert').hide();
		$("#jqxTree").jqxTree('selectItem', null);
		$scope.selectedItem = '';
	};
	
	/**
	* Delete a document
	*/
	$scope.deleteDocumentCommand = function()
	{
		console.info("deleteDocumentCommand - called"); 	
		
		$scope.removeTreeviewDataSource();
		var pathToDelete = $scope.selectedItem.path;
		if($scope.selectedItem.isfolder == false)
		{
			pathToDelete += '/' + $scope.selectedItem.label;
		}
		$scope.canManageDocument = false;

		$http.post($scope.servicebase, { "service" : "deleteDocument", "path" : pathToDelete }).
		success(function(data, status)
		{
			console.info("deleteDocumentCommand - call sucess"); 
			$scope.status = status;
			$scope.data = data;
			$scope.result = data;
			
			if($scope.data.isFailed == true)
			{
				$scope.setMessageCommand($scope.data.exception, 'danger');
			}
			else
			{
				$scope.canManageDocument = false;
				$scope.cancelSelectedDocumentCommand();
				$scope.getDocuments("");
				$("#confirmDeleteDocument").modal('hide');
				$scope.setMessageCommand('Document supprimé.', 'info');
			}
		})
		.
		error(function(data, status) 
		{
			console.error("deleteDocumentCommand - call failed"); 	
			$scope.canManageDocument = false;
			$scope.data = data || "Request failed";
			$scope.status = status;			
			console.log($scope.data); 		
			console.error("deleteDocumentCommand - data : " + $scope.data); 				
		});
	};
	
	/**
	* Cancel the document deletion
	*/
	$scope.cancelDeleteDocumentCommand = function()
	{
		$("#confirmDeleteDocument").modal('hide');
	};
	
	/**
	* Download a document
	*/
	$scope.downloadDocumentCommand = function()
	{
		console.info("downloadDocumentCommand - called"); 	
		
		if($scope.selectedItem.isfolder == false)
		{
			var path = $scope.selectedItem.path + '/' + $scope.selectedItem.label;
			
			console.info("downloadFileClient - call downloadFileClient with path : " + String(path)); 
			
			$http.post($scope.servicebase, { "service" : "createTempDocument", "sourcePath" : String(path) }).
			success(function(data, status) 
			{
				console.info("downloadFileClient - call sucess");
				$scope.status = status;
				$scope.data = data;
				$scope.result = data;
				
				if($scope.data.isFailed == true)
				{
					$scope.setMessageCommand($scope.data.exception, 'danger');
				}
				else
				{
					var url = JSON.parse(data);
					$scope.downloadUrl = url;
					$scope.canDownloadAttachment = true;
				}
			})
			.
			error(function(data, status) 
			{
				console.error("downloadFileClient - call failed"); 
				$scope.loadingDocuments = false;
				$scope.canManageTree = true;
				$scope.data = data || "Request failed";
				$scope.status = status;			
				console.error("downloadFileClient - data : " + $scope.data); 		
			});
		}
		else
		{
			$scope.setMessageCommand('Impossible de télécharger un dossier', 'warning');
		}
	};
	
	/**
	* Upload the document
	*/
	$scope.uploadFileCommand = function(files) 
	{
		console.info("uploadFileCommand - called"); 	
		$("#jqxProgressBar").jqxProgressBar({ value: 0 });
		$scope.removeTreeviewDataSource();
		$scope.uploadingDocument = true;
		$scope.canUpload = false;

		for (index = 0; index < files.length; ++index)
		{
			var percent = (100 * index + 1) / files.length;
		
			console.info("uploadFileCommand - call uploadDocumentsClient with index : " + index); 
			
			var fd = new FormData();
			fd.append("service", "uploadDocument");
			fd.append("file", files[index]);
			fd.append("rootpath", $scope.selectedItem.path);
			$http.post($scope.servicebase,
			fd,
			{ 
				withCredentials: true, headers: {'Content-Type': undefined }, transformRequest: angular.identity 
			}
			).
			success(function(data, status) 
			{
				console.info("uploadFileCommand - call success");
				
				if(data.isFailed == true)
				{
					$scope.setMessageCommand(data.exception, 'danger');
				}
				else
				{
					$scope.removeTreeviewDataSource();
					$scope.getDocuments("");
					$scope.uploadingDocument = false;
					$scope.canUpload = true;
					$("#file").val(null);
				}
			})
			.
			error(function(data, status) 
			{
				console.error("uploadFileCommand - call failed"); 
				$scope.uploadingDocument = false;
				$scope.canUpload = true;	
				console.error("uploadFileCommand - data : " + $scope.data); 					
			});
			
			$("#jqxProgressBar").jqxProgressBar({ value: percent });
		}
		
		$("#jqxProgressBar").jqxProgressBar({ value: 100 });
		//$("#uploadDocument").modal('hide');
	};
	
	/**
	* Set the treeview data source on cookie
	*/
	$scope.setTreeviewDataSource = function(data)
	{
		console.info("setTreeviewDataSource - called with data : " + data); 
		if(typeof(Storage) !== "undefined") 
		{
			localStorage.setItem("TreeviewDataSource", data);
		} 
		else 
		{
			$cookieStore.put("TreeviewDataSource", data);
		}
	};
	
	/**
	* Get the treeview data source from cookie
	*/
	$scope.getTreeviewDataSource = function()
	{
		console.info("getTreeviewDataSource - called"); 
		if(typeof(Storage) !== "undefined" || typeof(Storage) !== undefined) 
		{
			$scope.treeviewDataSource = localStorage.getItem("TreeviewDataSource");
		} 
		else 
		{
			$scope.treeviewDataSource = $cookieStore.get('TreeviewDataSource');
		}
		
		return $scope.treeviewDataSource;
	};
	
	/**
	* Remove the treeview data source from cookie
	*/
	$scope.removeTreeviewDataSource = function()
	{
		console.info("removeTreeviewDataSource - called"); 
		if(typeof(Storage) !== "undefined") 
		{
			$scope.treeviewDataSource = localStorage.removeItem("TreeviewDataSource");
		} 
		else 
		{
			$scope.treeviewDataSource = $cookieStore.remove('TreeviewDataSource');
		}
	};
	
	/**
	* Command to cancel the current filter
	*/
	$scope.cancelFilterCommand = function()
	{
		console.info("cancelFilterCommand - called");
		$scope.removeTreeviewDataSource();
		$scope.filterClicked = false;
		$scope.documentFilter = '';
		$scope.selectedItem = '';
		$scope.getDocuments("");
	};
	
	/**
	* Deprecated : Get recursive documents command
	*/
	$scope.getRecursiveDocuments = function() 
	{
		console.info("getRecursiveDocuments - called");
		$scope.loadingDocuments = true;
		$scope.canManageTree = false;
	
		if($scope.documentFilter != '')
		{
			$scope.removeTreeviewDataSource();
		}
		
		var datasource = $scope.getTreeviewDataSource();
		
		if(datasource == null || datasource == "")
		{ 
			console.info("getRecursiveDocuments - datasource is null");
			
			$http.post($scope.servicebase, { "service" : "getDocuments", "root" : "none", "forceToRefresh" : true, "filter" : $scope.documentFilter }).
			success(function(data, status) 
			{
				console.info("getRecursiveDocuments - call success");
				$scope.status = status;
				$scope.data = data;
				$scope.result = data;
				console.info("result of getRecursiveDocumentsClient : " + JSON.stringify($scope.data)); 	

				if(data.isFailed == true)
				{
					$scope.setMessageCommand($scope.data.exception, 'danger');
				}
				else
				{
					if(data.response != undefined)
					{
						var source = $scope.buildData(data.response);
						$scope.setTreeviewDataSource(JSON.stringify(data.response));
						$('#jqxTree').jqxTree({ allowDrag:true, allowDrop:true, source: source, width: '100%', height: '400px'});
					}
					$scope.loadingDocuments = false;
					$scope.canManageTree = true;
				}
			})
			.
			error(function(data, status) 
			{
				console.error("getRecursiveDocuments - call failed"); 
				$scope.loadingDocuments = false;
				$scope.canManageTree = true;
				$scope.data = data || "Request failed";
				$scope.status = status;			
				console.error($scope.data); 
				console.error("getRecursiveDocuments - data : " + $scope.data); 						
			});
		}
		else
		{
			console.info("getRecursiveDocuments - datasource is set");
			var cookie = $scope.getTreeviewDataSource();
			console.info('cookie value = ' + cookie);
			var source = $scope.buildData(JSON.parse(cookie));
			$('#jqxTree').jqxTree({ allowDrag:true, allowDrop:true, source: source, width: '100%', height: '400px'});
			$scope.loadingDocuments = false;
			$scope.canManageTree = true;
		}
	};
	
	/**
	* Command to create a folder
	*/
	$scope.createFolderCommand = function() 
	{
		console.info("createFolderCommand - called"); 	
		
		//$scope.removeTreeviewDataSource();
		//$scope.canUpload = false;
		var path = undefined;
		
		if($scope.selectedItem == '')
		{
			path = "";
		}
		else
		{
			path = $scope.selectedItem.path;
		}
		
		$http.post($scope.servicebase, { "service" : "createFolder", "path" : path, "name": $scope.createNewFolderName.whithoutAccent() }).
		success(function(data, status) 
		{
			console.info("createFolderCommand - call success");
			$scope.status = status;
			$scope.data = data;
			$scope.result = data;
			if(data.isFailed == true)
			{
				$scope.setMessageCommand($scope.data.exception, 'danger');
			}
			else
			{
				$("#newFolder").modal('hide');
				$scope.setMessageCommand("Dossier créé", 'success');
			}
			$scope.getDocuments(path);
		})
		.
		error(function(data, status) 
		{
			console.error("createFolderCommand - call failed"); 
			$scope.loadingDocuments = false;
			$scope.canManageTree = true;
			$scope.data = data || "Request failed";
			$scope.status = status;			
			console.error("createFolderCommand - data : " + $scope.data); 		
		});
	};
	
	/**
	* Rename the document
	*/
	$scope.renameDocumentCommand = function()
	{
		console.info("renameDocumentCommand called");
		$scope.removeTreeviewDataSource();
		var newName = $scope.newDocumentName.whithoutAccent();
		var oldName = $scope.selectedItem.label;
		var path = $scope.selectedItem.path;
		
		if($scope.selectedItem.isfolder)
		{
			path = path.replace(oldName, ""); 
		}

		$scope.loadingDocuments = true;
		$scope.canManageTree = false;

		console.info("renameDocumentCommand - call renameDocument with path : " + path + " newName " + newName + " oldName " + oldName);
		
		$http.post($scope.servicebase, { "service" : "renameDocument", "path" : path, "newName" : newName, "oldName" : oldName }).
		success(function(data, status) 
		{
			console.info("renameDocumentCommand - call success"); 	
			$scope.status = status;
			$scope.data = data;
			$scope.result = data;
			
			if($scope.data.isFailed == true)
			{
				$scope.setMessageCommand($scope.data.exception, 'danger');
			}
			else
			{
				$scope.getDocuments("");
				$scope.selectedItem.label = newName;
				$("#renameDocument").modal('hide');
			}
		})
		.
		error(function(data, status) 
		{
			console.error("renameDocumentCommand - call failed"); 	
			$scope.loadingDocuments = false;
			$scope.canManageTree = true;
			$scope.data = data || "Request failed";
			$scope.status = status;			
			console.error("renameDocumentCommand - data : " + $scope.data); 				
		});
	};
		
	/**
	* Load the document component
	*/
	$scope.loadDocumentsControllerCommand = function() 
	{
		
		console.info("loadDocumentsComponentCommand - called");

		angular.module('cdf91680', ['ngCookies']);

		console.info("Set default variables");
		$scope.loadingDocuments = false;
		$scope.canManageTree = true;
		$scope.uploadingDocument = false;
		$scope.canUpload = true;
		$scope.canManageDocument = false;
		$scope.selectedItem = '';
		$scope.downloadUrl = '';
		$scope.canDownload = false;
		$scope.documentFilter = '';
		$("#file").val(null);
		
		$scope.getDocuments("");
	};
	
	$scope.loadDocumentsControllerCommand();
}]);